package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.em.wechat.AuthorizerCode;
import com.pactera.madp.cp.api.entity.BaseEntity;
import com.pactera.madp.cp.api.entity.authorizer.AuthorizerEntity;
import com.pactera.madp.cp.api.entity.marketing.MarketingArticleEntity;
import com.pactera.madp.cp.api.feign.WxComponentFeign;
import com.pactera.madp.cp.api.model.WechatResponse;
import com.pactera.madp.cp.api.model.authorization.ApiStartPushTicketRequest;
import com.pactera.madp.cp.api.model.authorization.GetPreAuthCodeResponse;
import com.pactera.madp.cp.api.model.authorization.OfficialAccountPreCodeResponse;
import com.pactera.madp.cp.api.vo.wechat.WechatAuthorizerListVO;
import com.pactera.madp.cp.api.vo.wechat.WechatMarketingVO;
import com.pactera.madp.cp.common.config.WechatComponentConfig;
import com.pactera.madp.cp.common.constant.WxJsonConst;
import com.pactera.madp.cp.common.constant.WxGZHApiConst;
import com.pactera.madp.cp.common.util.HttpClientUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mp.AesException;
import com.pactera.madp.cp.mp.WXBizMsgCrypt;
import com.pactera.madp.cp.mp.XMLParse;
import com.pactera.madp.cp.service.AuthorizerService;
import com.pactera.madp.cp.service.CacheService;
import com.pactera.madp.cp.service.MarketingArticleService;
import com.pactera.madp.cp.service.WechatComponentService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: chenhao
 * @date: 2021/7/15 17:54
 * @description: 微信授权流程实现层
 */
@Slf4j
@Service("wechatComponentService")
public class WechatComponentServiceImpl implements WechatComponentService {

    private static final Logger logger = LoggerFactory.getLogger(WechatComponentServiceImpl.class);
    @Autowired
    private WxComponentFeign wxComponentFeign;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private AuthorizerService authorizerService;
    @Autowired
    private MarketingArticleService articleService;

    @Override
    public WechatResponse startPushTicket() {
        ApiStartPushTicketRequest apiStartPushTicketRequest = new ApiStartPushTicketRequest();
        apiStartPushTicketRequest.setComponent_appid(WechatComponentConfig.appId);
        apiStartPushTicketRequest.setComponent_secret(WechatComponentConfig.appSecret);
        return wxComponentFeign.startPushTicket(apiStartPushTicketRequest);
    }

    @Override
    public String decryptWechatMessage(String msgSignature, String timestamp, String nonce, String msg) {
        try {
            Integer corpId = CorpContextHolder.getCorpId();
            Long size = redisTemplate.opsForList().size("cp:"+corpId+".encrypt");
            String encrypt = redisTemplate.opsForList().index("cp:"+corpId+".encrypt", size-1);
            WXBizMsgCrypt decryptMsg = new WXBizMsgCrypt("PhdYjF63Q72D38T7MaDp", "2xDNCRH4RZLG8DHyc8ENWd7LtjzrzV4MsgKer6EMaDp", "wxb79a5493081e3d80");
            String decryptmsg = decryptMsg.decrypt(encrypt);
            log.info("decryptmsg = " + decryptmsg);
            String[] params = new String[]{"ComponentVerifyTicket"};
            Object[] componentVerifyTicket = XMLParse.extract(decryptmsg, params);
            String ticket = (String)componentVerifyTicket[0];
            setComponentVerifyTicket(ticket);
            log.info("ticket = " + ticket);
            return ticket;
        } catch (AesException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void setComponentVerifyTicket(String ticket) {
        Integer corpId = CorpContextHolder.getCorpId();
        if (StringUtils.isNotEmpty(ticket)) {
            // component_verify_ticket 的有效时间为2小时。
            this.redisTemplate.opsForValue().set(StrUtil.format("cp:"+corpId+".{}",WechatComponentConfig.CACHE_COMPONENT_VERIFY_TICKET),ticket);
            this.redisTemplate.expire("cp:"+corpId+"."+WechatComponentConfig.CACHE_COMPONENT_VERIFY_TICKET, 2, TimeUnit.HOURS);
        }
    }

    @Override
    public String getComponentVerifyTicket() {
        Integer corpId = CorpContextHolder.getCorpId();
        String ticket = this.redisTemplate.opsForValue().get("cp:"+corpId+"."+WechatComponentConfig.CACHE_COMPONENT_VERIFY_TICKET);
        if(StringUtils.isEmpty(ticket)){
            return decryptWechatMessage(null, null, null, null);
        }
        return ticket;
    }

    @Override
    public String getComponentAccessToken() {
        Integer corpId = CorpContextHolder.getCorpId();
        // 从缓存中获取ComponentAccessToken, 过期再请求微信更新
        String componentAccessToken = cacheService.selectCache("cp:"+corpId+"."+WechatComponentConfig.CACHE_COMPONENT_ACCESS_TOKEN);
        log.info("componentAccessToken="+componentAccessToken);
        if (StringUtils.isNotEmpty(componentAccessToken)) {
            return componentAccessToken;
        }
        return   componentAccessToken();
    }

    @Override
    public String componentAccessToken() {
        Integer corpId = CorpContextHolder.getCorpId();
        String token = redisTemplate.opsForValue().get("cp:"+corpId+"."+WechatComponentConfig.CACHE_COMPONENT_ACCESS_TOKEN);
       log.info("token="+token);
        if(StringUtils.isNotEmpty(token)) {
            return token;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.COMPONENT_APP_ID, WechatComponentConfig.appId);
        jsonObject.put(WxJsonConst.COMPONENT_SECRET,WechatComponentConfig.appSecret);
        jsonObject.put(WxJsonConst.COMPONENT_VERIFY_TICKET,getComponentVerifyTicket());
        String requestBody = jsonObject.toString();
        log.info("requestBody="+requestBody);
        String url= WxGZHApiConst.API_COMPONENT_TOKEN_URL;
        log.info("url = " + url);
        String result = doPostResult(url, requestBody);
        log.info("result = " + result);
        JSONObject resp = JSONObject.parseObject(result);
        //授权信息说明
        if(StringUtils.isNotEmpty(resp.getString("errcode"))){
            if("61005".equals(resp.getString("errcode"))){
                redisTemplate.delete(WechatComponentConfig.CACHE_COMPONENT_VERIFY_TICKET);
            }
            throw new CheckedException(resp.getString("errmsg"));
        }
        String componentAccessToken = resp.getString(WxJsonConst.COMPONENT_ACCESS_TOKEN);
        String expiresIn = resp.getString(WxJsonConst.EXPIRES_IN);
        log.info("componentAccessToken="+componentAccessToken);
        log.info("expiresIn="+expiresIn);
        // 缓存第三方平台的ComponentAccessToken
        cacheService.saveComponentToken(StrUtil.format("cp:"+corpId+".{}",WechatComponentConfig.CACHE_COMPONENT_ACCESS_TOKEN), componentAccessToken);
        return componentAccessToken;
    }

    @Override
    public String getPreAuthCode() {
        Integer corpId = CorpContextHolder.getCorpId();
        String preAuthCode = cacheService.selectCache("cp:"+corpId+"."+WechatComponentConfig.CACHE_PRE_AUTH_CODE);
        log.info("preAuthCode="+preAuthCode);
        if (StringUtils.isNotEmpty(preAuthCode)) {
            return preAuthCode;
        }
        GetPreAuthCodeResponse getPreAuthCodeResponse = preAuthCode();
        log.info("getPreAuthCodeResponse="+getPreAuthCodeResponse);
        return getPreAuthCodeResponse.getPreAuthCode();

    }

    @Override
    public String getUserAuthorization() throws UnsupportedEncodingException {
        //获取预授权码
        String preAuthCode = getPreAuthCode();
        log.info("preAuthCode="+preAuthCode);
        String encode = URLEncoder.encode("http://i31602138y.wicp.vip/#/customers-into/marketing-material/index?component_appid="+WechatComponentConfig.appId, "UTF-8");
        //服务方的appId
        String componentAppId = WechatComponentConfig.appId;
        String url= WxGZHApiConst.OFFICIAL_ACCOUNT_URL +"?component_appid="
                +componentAppId+"&pre_auth_code="
                +preAuthCode+"&redirect_uri="
                +encode+"&auth_type="
                +3;
        return url;
    }

    @Override
    public OfficialAccountPreCodeResponse getUserAuthorizationAccessToken(String appId,String code) {
        Integer corpId = CorpContextHolder.getCorpId();
        //获取服务方的accessToken
        String componentAccessToken = getComponentAccessToken();
        String url = WxGZHApiConst.ACCESS_TOKEN + "?component_access_token="
                + componentAccessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.COMPONENT_APP_ID, WechatComponentConfig.appId);
        jsonObject.put(WxJsonConst.AUTHORIZATION_CODE, code);
        String requestBody = jsonObject.toString();
        String result = doPostResult(url, requestBody);
        JSONObject resp = JSONObject.parseObject(result);
        if (null != result) {
            try {
                //授权信息说明
                String authorizationInfo = resp.getString(WxJsonConst.AUTHORIZATION_INFO);
                JSONObject authorizationList = JSONObject.parseObject(authorizationInfo);
                //授权方 appId
                String authorizerAppId = authorizationList.getString(WxJsonConst.AUTHORIZER_APP_ID);
                //接口调用令牌
                String authorizerAccessToken = authorizationList.getString(WxJsonConst.AUTHORIZER_ACCESS_TOKEN);
                // authorizerAccessToken 有效期
                String expiresIn = authorizationList.getString(WxJsonConst.EXPIRES_IN);
                //刷新令牌
                String authorizerRefreshToken = authorizationList.getString(WxJsonConst.AUTHORIZER_REFRESH_TOKEN);
                //授权给开发者的权限集列表
                String funcInfo = resp.getString(WxJsonConst.FUNC_INFO);
                //将授权令牌存入缓存中
                cacheService.saveAuthorizerToken(StrUtil.format("cp:"+corpId+".{}",WechatComponentConfig.CACHE_AUTHORIZER_TOKEN + authorizerAppId), authorizerAccessToken);
                //将授权刷新令牌存入缓存中
                cacheService.saveRefreshToken(StrUtil.format("cp:"+corpId+".{}",WechatComponentConfig.CACHE_AUTHORIZER_REFRESH_TOKEN + authorizerAppId), authorizerRefreshToken);
                //返回对象
                OfficialAccountPreCodeResponse response = new OfficialAccountPreCodeResponse();
                response.setAuthorizerAccessToken(authorizerAccessToken);
                response.setExpiresIn(expiresIn);
                response.setRefreshToken(authorizerRefreshToken);
                response.setAuthorizerAppId(authorizerAppId);
                return response;
            } catch (JSONException e) {
                // 获取Material失败
                log.error("获取Material失败 errcode:{} errmsg:{}", resp.getInteger("errcode"), resp.getString("errmsg"));
                return null;
            }
        }
        return null;
    }
    @Override
    public String getAccessToken(String appId) {
        Integer corpId = CorpContextHolder.getCorpId();
        String accessToken = cacheService.selectCache("cp:"+corpId+"."+WechatComponentConfig.CACHE_AUTHORIZER_TOKEN + appId);
        if(StringUtils.isEmpty(accessToken)){
            String refreshToken = cacheService.selectCache("cp:"+corpId+"."+WechatComponentConfig.CACHE_AUTHORIZER_REFRESH_TOKEN + appId);
            return getAccessTokenByRefreshToken(appId, refreshToken);
        }
        return accessToken;
    }

    @Override
    public String getAccessTokenByRefreshToken(String appId,String refreshToken) {
        Integer corpId = CorpContextHolder.getCorpId();
        String componentAccessToken = getComponentAccessToken();
        String url= WxGZHApiConst.OFFICIAL_REFRESH_URL+"?component_access_token="+componentAccessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.COMPONENT_APP_ID, WechatComponentConfig.appId);
        jsonObject.put(WxJsonConst.AUTHORIZER_APP_ID, appId);
        jsonObject.put(WxJsonConst.AUTHORIZER_REFRESH_TOKEN, refreshToken);
        String requestBody = jsonObject.toString();
        String result = doPostResult(url, requestBody);
        JSONObject resp = JSONObject.parseObject(result);
        String errcode = resp.getString("errcode");
        //接口调用令牌
        String authorizerAccessToken = resp.getString(WxJsonConst.AUTHORIZER_ACCESS_TOKEN);
        //刷新令牌
        String authorizerRefreshToken = resp.getString(WxJsonConst.AUTHORIZER_REFRESH_TOKEN);
        if(null==authorizerRefreshToken){
             log.debug("此账号还未授权！");
             if("61003".equals(errcode)){
                 authorizerService.remove(Wrappers.<AuthorizerEntity>lambdaQuery().eq(AuthorizerEntity::getAuthorizerAppId,appId));
                 articleService.remove(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getAuthorizerAppId,appId));
             }
            cacheService.deleteCache("cp:"+corpId+"."+WechatComponentConfig.CACHE_AUTHORIZER_REFRESH_TOKEN+appId);
           throw new CheckedException(resp.getString("errmsg"));
        }
        //将授权令牌存入缓存中
        cacheService.saveAuthorizerToken("cp:"+corpId+"."+WechatComponentConfig.CACHE_AUTHORIZER_TOKEN+appId,authorizerAccessToken);
        return authorizerAccessToken;
    }

    @Override
    @SneakyThrows
    public void getMarketingList(String appId, Integer classification, String type, Integer offset, Integer count) {
        Integer corpId = CorpContextHolder.getCorpId();
        String accessToken = getAccessToken(appId);
        String getUrl= WxGZHApiConst.GET_MATERIAL_URL+"?access_token="+accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.TYPE, "news");
        jsonObject.put(WxJsonConst.OFFSET, offset);
        jsonObject.put(WxJsonConst.COUNT, count);
        String requestBody = jsonObject.toString();
        String result = doPostResult(getUrl, requestBody);
        JSONObject parseObject = JSONObject.parseObject(result);
        if(StringUtils.isNotEmpty(parseObject.getString("errcode"))){
            log.debug("errcode:{},errmsg:{}",parseObject.getString("errcode"),parseObject.getString("errmsg"));
            throw  new CheckedException(parseObject.getString("errmsg"));
        }
        //素材总数
        String totalCount = parseObject.getString("total_count");
        //当前获取素材数
        String itemCount = parseObject.getString("item_count");
        //文章数组
        String item = parseObject.getString("item");
            JSONArray jsonArray = JSONArray.parseArray(item);
                WechatMarketingVO wechatMarketingVO = new WechatMarketingVO();
                wechatMarketingVO.setItemCount(Integer.valueOf(itemCount));
                wechatMarketingVO.setTotalCount(Integer.valueOf(totalCount));
                for (int i = 0; i < jsonArray.toArray().length; i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    //素材唯一id
                    String mediaId = object.getString("media_id");
                    //素材内容
                    String content = object.getString("content");
                    String updateTime = object.getString("update_time");
                    //多图文数组
                    String newsItem = JSONObject.parseObject(content).getString("news_item");
                    JSONArray array = JSONArray.parseArray(newsItem);
                    WechatMarketingVO.MarketingListVO marketingListVO = new WechatMarketingVO.MarketingListVO();
                    marketingListVO.setContent(content);
                    marketingListVO.setMediaId(mediaId);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    // clientTimeStamp为秒，需要转换为毫秒，再转换为年月日时分秒
                    String currentTime = dateFormat.format(new Date(Long.valueOf(updateTime + "000")));
                    marketingListVO.setUpdateTime(currentTime);
                    for (int j = 0; j < array.toArray().length; j++) {
                        //图文内容
                        JSONObject arrayObject = array.getJSONObject(j);
                        //标题
                        String title = arrayObject.getString("title");
                        title = URLDecoder.decode(new String(title.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.CHARSET_UTF_8));
                        //图文唯一id
                        String thumbMediaId = arrayObject.getString("thumb_media_id");
                        log.info("thumbMediaId = " + thumbMediaId);
                        //是否显示封面
                        String showCoverPic = arrayObject.getString("show_cover_pic");
                        log.info("showCoverPic = " + showCoverPic);
                        //封面地址
                        String thumbUrl = arrayObject.getString("thumb_url");
                        log.info("thumbUrl = " + thumbUrl);
                        //作者
                        String author = arrayObject.getString("author");
                        author = URLDecoder.decode(new String(author.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.CHARSET_UTF_8));
                        //摘要
                        String digest = arrayObject.getString("digest");
                        digest = URLDecoder.decode(new String(digest.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.CHARSET_UTF_8));
                        //图文地址
                        String url = arrayObject.getString("url");
                        if (null == articleService.getOne(Wrappers.<MarketingArticleEntity>lambdaQuery()
                                .eq(MarketingArticleEntity::getCorpId, corpId)
                                .eq(BaseEntity::getDelFlag, 0)
                                .eq(MarketingArticleEntity::getAuthorizerAppId, appId)
                                .eq(MarketingArticleEntity::getMediaId, mediaId)
                                .eq(MarketingArticleEntity::getClassification, classification))) {
                            MarketingArticleEntity articleEntity = new MarketingArticleEntity();
                            articleEntity.setTitle(title);
                            articleEntity.setMarketingUrl(url);
                            articleEntity.setMarketingState(1);
                            articleEntity.setMarketingDescribe(digest);
                            articleEntity.setArAuthor(author);
                            articleEntity.setArAttribute(1);
                            articleEntity.setCorpId(corpId);
                            articleEntity.setMediaId(mediaId);
                            articleEntity.setAuthorizerAppId(appId);
                            articleEntity.setClassification(classification);
                            articleEntity.setMarketingCover(thumbUrl);
                            boolean save = articleService.save(articleEntity);
                            if(!save){
                                throw new CheckedException("素材获取失败！");
                            }
                        }else {
                            MarketingArticleEntity articleEntity = new MarketingArticleEntity();
                            articleEntity.setTitle(title);
                            articleEntity.setMarketingUrl(url);
                            articleEntity.setMarketingDescribe(digest);
                            articleEntity.setArAuthor(author);
                            articleEntity.setMediaId(mediaId);
                            articleEntity.setAuthorizerAppId(appId);
                            articleEntity.setMarketingCover(thumbUrl);
                            articleEntity.setUpdateTime(LocalDateTime.now());
                            boolean update = articleService.update(articleEntity, Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getMediaId, mediaId).eq(MarketingArticleEntity::getCorpId,corpId).eq(MarketingArticleEntity::getClassification,classification));
                            if(!update){
                                throw new CheckedException("素材同步失败！");
                            }
                        }
                    }
                }
    }

    @Override
    public List<WechatAuthorizerListVO> getAuthorizerList(Integer offset, Integer count) {
        Integer corpId = CorpContextHolder.getCorpId();
        String componentAccessToken = getComponentAccessToken();
        String url= WxGZHApiConst.API_GET_AUTHORIZER_LIST+"?component_access_token="+componentAccessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.COMPONENT_APP_ID, WechatComponentConfig.appId);
        jsonObject.put(WxJsonConst.OFFSET, offset);
        jsonObject.put(WxJsonConst.COUNT, count);
        String requestBody = jsonObject.toString();
        String result = doPostResult(url, requestBody);
            //授权总数
            String totalCount = JSONObject.parseObject(result).getString("total_count");
            JSONArray array = JSONArray.parseArray(JSONObject.parseObject(result).getString("list"));
            for (int i = 0; i < array.toArray().length; i++) {
                JSONObject object = array.getJSONObject(i);
                //授权号的appId
                String authorizerAppId = object.getString("authorizer_appid");
                log.info("authorizerAppId = " + authorizerAppId);
                String refreshToken = object.getString("refresh_token");
                //缓存新的刷新令牌
                cacheService.saveRefreshToken(StrUtil.format("cp:"+corpId+".{}",WechatComponentConfig.CACHE_AUTHORIZER_REFRESH_TOKEN+authorizerAppId),refreshToken);
                //授权时间
                String authTime = object.getString("auth_time");
                log.info("authTime = " + authTime);
                String infoUrl= WxGZHApiConst.API_GET_AUTHORIZER_INFO+"?component_access_token="+componentAccessToken;
                JSONObject jsonInfo = new JSONObject();
                jsonInfo.put(WxJsonConst.COMPONENT_APP_ID, WechatComponentConfig.appId);
                jsonInfo.put(WxJsonConst.AUTHORIZER_APP_ID, authorizerAppId);
                String requestBodyInfo = jsonInfo.toString();
                String resultInfo = doPostResult(infoUrl, requestBodyInfo);
                JSONObject infoResult = JSONObject.parseObject(resultInfo).getJSONObject("authorizer_info");
                //公众号昵称
                String nickName = infoResult.getString("nick_name");
                //公众号头像
                String headImg = infoResult.getString("head_img");
                //主体名称
                String userName = infoResult.getString("user_name");
                Integer serviceTypeInfo =Integer.parseInt(infoResult.getJSONObject("service_type_info").getString("id"));
               if(null==authorizerService.getOne(Wrappers.<AuthorizerEntity>lambdaQuery().eq(AuthorizerEntity::getCorpId,corpId).eq(AuthorizerEntity::getAuthorizerAppId,authorizerAppId))){
                   AuthorizerEntity authorizerEntity = new AuthorizerEntity();
                   authorizerEntity.setAuthorizerAppId(authorizerAppId);
                   authorizerEntity.setAuthTime(authTime);
                   authorizerEntity.setHeadImg(headImg);
                   authorizerEntity.setServiceTypeInfo(serviceTypeInfo);
                   authorizerEntity.setNickName(nickName);
                   authorizerEntity.setUserName(userName);
                   authorizerEntity.setCorpId(corpId);
                   authorizerService.save(authorizerEntity);
               }
            }
        List<WechatAuthorizerListVO> vos = authorizerService.list(Wrappers.<AuthorizerEntity>lambdaQuery()
                .eq(AuthorizerEntity::getCorpId, corpId)).stream().map(entity -> {
            WechatAuthorizerListVO vo = new WechatAuthorizerListVO();
            vo.setAuthorizerAppId(entity.getAuthorizerAppId());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // clientTimeStamp为秒，需要转换为毫秒，再转换为年月日时分秒
            String currentTime = dateFormat.format(new Date(Long.valueOf(entity.getAuthTime() + "000")));
            vo.setAuthTime(currentTime);
            vo.setHeadImg(entity.getHeadImg());
            vo.setNickName(entity.getNickName());
            vo.setUserName(entity.getUserName());
            vo.setServiceTypeInfo(AuthorizerCode.getTypeByCode(entity.getServiceTypeInfo()));
            vo.setStatus(entity.getStatus());
            return vo;
        }).collect(Collectors.toList());
            return vos;
    }

    @Override
    public void saveTicketToRedis(String encrypt) {
        LinkedList<String> strings = new LinkedList<>();
        Integer corpId = CorpContextHolder.getCorpId();
        strings.add(encrypt);
        String template= StrUtil.format("cp:"+corpId+".{}","encrypt");
        Long size = redisTemplate.opsForList().size(template);
        if (size>0) {
            int array = 10;
            if (size + 1 > array) {
                redisTemplate.opsForList().rightPop(template);
            }
        }
        redisTemplate.opsForList().leftPush(template,encrypt);
    }

    @Override
    public String materialInfo(String appId,String mediaId) {
        String accessToken = getAccessToken(appId);
        String url=WxGZHApiConst.GET_MATERIAL+"?access_token="+accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.MEDIA_ID, mediaId);
        String requestBody = jsonObject.toString();
        return doPostResult(url,requestBody);
    }

    @Override
    public void changeState(String appIds) {
        Integer corpId = CorpContextHolder.getCorpId();
        UpdateWrapper<AuthorizerEntity> wrapper1 = new UpdateWrapper<>();
        wrapper1.set("status",1).eq("corp_id",corpId);
        authorizerService.update(null,wrapper1);
        String[] split = appIds.split(",");
        for (int i = 0; i < split.length; i++) {
            String appId = split[i];
            UpdateWrapper<AuthorizerEntity> wrapper = new UpdateWrapper<>();
            wrapper.set("status",2).eq("authorizer_app_id",appId);
            authorizerService.update(null,wrapper);
        }
    }

    @Override
    public List<WechatAuthorizerListVO> getAuthorizerListByState() {
        Integer corpId = CorpContextHolder.getCorpId();
     return    authorizerService.list(Wrappers.<AuthorizerEntity>lambdaQuery()
                .eq(AuthorizerEntity::getStatus,2).eq(BaseEntity::getDelFlag,0)
                .eq(AuthorizerEntity::getCorpId,corpId)
                .orderByDesc(AuthorizerEntity::getId)).stream().map(entity->{
            WechatAuthorizerListVO vo = new WechatAuthorizerListVO();
            BeanUtil.copyProperties(entity,vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public GetPreAuthCodeResponse preAuthCode() {
        Integer corpId = CorpContextHolder.getCorpId();
        String componentAccessToken = getComponentAccessToken();
        log.info("componentAccessToken = " + componentAccessToken);
         String url= WxGZHApiConst.PRE_AUTH_CODE_URL+"?component_access_token="+getComponentAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(WxJsonConst.COMPONENT_APP_ID, WechatComponentConfig.appId);
        String requestBody = jsonObject.toString();
        String response = doPostResult(url, requestBody);
        JSONObject resp = JSONObject.parseObject(response);
            String preAuthCode = resp.getString(WxJsonConst.PRE_AUTH_CODE);
            String expiresIn = resp.getString(WxJsonConst.EXPIRES_IN);
            log.info("expires_in="+expiresIn);
        if (logger.isDebugEnabled()) {
            logger.debug("preAuthCode:{}", response);
        }
        cacheService.saveTempVaCode(corpId+":"+WechatComponentConfig.CACHE_PRE_AUTH_CODE, preAuthCode);
        GetPreAuthCodeResponse getPreAuthCodeResponse = new GetPreAuthCodeResponse();
        getPreAuthCodeResponse.setPreAuthCode(preAuthCode);
        getPreAuthCodeResponse.setExpiresIn(Integer.parseInt(expiresIn));
        return getPreAuthCodeResponse;
    }


    /**
     * 跳转链接-post
     *
     * @param url
     * @param requestBody
     * @return
     */
    private static String doPostResult(String url,String requestBody) {
        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
        log.debug("url: " + url);
        log.debug("requestBody: " + requestBody);
        String respJson = HttpClientUtil.doPost(url, requestBody);
        log.debug("respJson: " + respJson);
        log.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
        return respJson;
    }

    /**
     * 跳转链接-get
     *
     * @param url
     * @return
     */
    private static String doGetResult(String url) {
        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
        log.debug("url: " + url);
        String respJson = HttpClientUtil.doGet(url);
        log.debug("respJson: " + respJson);
        log.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
        return respJson;
    }
}


